<?php

namespace App\Http\Middleware;

use Closure;
use Log;
use App\Http\Responses\Response;


class RenderMiddleware
{
    public $message = 'OK.';
    public $level   = 'debug';
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
		log::info($request->path().' '.collect($request->input()));  # 记录请求URL和请求参数

        $response = $next($request);
	   
		$cookie = $response->headers->getCookies();
		$headers['set-cookie'] = $cookie;
        if ($response->status() == 200) {
            if($request->header('status_flag') && $request->header('status_flag')==1)
            {
                return new Response($response->getOriginalContent(), 200, $headers,0);
            }
            return new Response($response->getOriginalContent(), $response->status(), $headers);
        } elseif ($response->exception) {
            $exception = $response->exception;
            // dd($exception->getCode());
            $this->message = sprintf(
                '%s:%d err:%s err_no:%s',
                $exception->getFile(),
                $exception->getLine(),
                $exception->getMessage(),
                $exception->getCode()
            );

            $this->level = 'warn';

            return new Response([], 200, $headers, $exception->getCode()?:$response->status(), $exception->getMessage());
        } elseif ($response->status() == 401) {
            $this->message = $response;
            $this->level = 'error';
            return new Response('', 200, $headers, $response->status(), $response->getOriginalContent());
        } else {
            $data = $response->getData(true);
            $this->level = 'error';
            $this->message = $response;
            return new Response($data, 200, $headers, $response->status());
        }
    }

    /**
     * terminate
     *
     * @param  mixed $request
     * @param  mixed $response
     * @access public
     * @return mixed
     */
    public function terminate($request, $response)
    {
        $this->message =  sprintf(
                '{"app-id":"%s","unique_id":"%s"} %s ',
                $request->header('app_id'),
                $request->header('unique_id'),
                $this->message
                );
        if ($this->level == 'debug') {
            $content = $response->getContent();
            $this->message .=strlen($content) >256 ? (substr($content, 0, 240).'...') : $content;
            if (config('log.default.level') == 'debug') {
                log :: debug ($request . ' '. $response.PHP_EOL);
            } else {
                Log :: notice($this->message.PHP_EOL);
            }
        }else {
            $this->message = str_replace("\n", '', $this->message);
            Log :: {$this->level}($this->message.PHP_EOL);
        }
    }
}
;
